package com.jeeplus.modules.sys.web;

import com.aspose.cells.*;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.service.DictTypeService;
import com.jeeplus.modules.sys.service.OrderCollectionService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.test.one.dialog.entity.Leave1;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SimpleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author Administrator
 * @title: 事农集单
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/9/1613:03
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/OrderCollection")
public class OrderCollectionController extends BaseController {
    @Autowired
    OrderCollectionService orderService;
    @Autowired
    DictTypeService dictTypeService;
    //region 页面
    @RequestMapping(value = {"", "list"})
    public String list(Leave1 leave1, Model model) {
        model.addAttribute("leave1", leave1);
        return "modules/sys/OrderCollection/OrderCollectionList";
    }

    @RequestMapping(value = "upload")
    public String upload(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "modules/sys/OrderCollection/upload";
    }
    @RequestMapping(value = "datetime")
    public String datetime(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "modules/sys/OrderCollection/datetime";
    }
    @RequestMapping(value = "buyerOrderDetail")
    public String buyerOrderDetail(Leave1 leave1, HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("leave1", leave1);
        return "modules/sys/OrderCollection/BuyerOrderDetail";
    }
    //endregion

    //region 数据

    /**
     * 获取数据
     *
     * @param leaveDialog
     * @param request
     * @param response
     * @param model
     * @return
     */
    @ResponseBody
    // @RequiresPermissions("test:one:leaveDialog:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(Leave1 leaveDialog, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Leave1> page = orderService.findPage(new Page<Leave1>(request, response), leaveDialog);
        return getBootstrapListData(page);
    }

    @ResponseBody
    @RequestMapping(value = "buyerOrderData")
    public Map<String, Object> buyerOrderData(Leave1 leaveDialog, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Leave1> page = orderService.BuyerOrderDetail(new Page<Leave1>(request, response), leaveDialog);

        return getBootstrapListData(page);
    }

    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = OrderImp.class.getClassLoader().getResourceAsStream("license.xml"); //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //endregion
    //region 功能
    //@RequiresPermissions("test:one:leaveDialog:import")

    /***
     * 导入数据
     *
     * @Author LH
     * @Description //TODO
     * @Date 6:47 2019/9/17
     * @param file
     * @param request
     * @param redirectAttributes
     * @return java.lang.String
     **/
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        try {
            String ordTime= DictUtils.getDictValue("OrderImpTime","OrderTime","").replace(":","");
            String currTime= DateUtils.getDate("HHmm");
            if(Integer.valueOf(currTime)>=Integer.valueOf(ordTime))
            {
                addMessage(redirectAttributes, "订货时间己过时");
                return "redirect:" + Global.getAdminPath() + "/sys/OrderCollection/?repage";
            }
            getLicense();
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            //ImportExcel ei = new ImportExcel(file, 1, 0);
            try {
                User currentUser = UserUtils.getUser();
                String officeCode = UserUtils.getOffice(currentUser.getCompany().getId()).getCode();
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                if (!new File(String.format("%s\\UserUpload\\%s\\%s\\", Global.getConfig("userfiles.basedir"), year, month)).exists()) {
                    FileUtils.createDirectory(String.format("%s\\UserUpload\\%s\\%s\\", Global.getConfig("userfiles.basedir"), year, month));
                }
                String fileName = String.format("%s\\UserUpload\\%s\\%s\\%s-%s", Global.getConfig("userfiles.basedir"), year, month, IdGen.uuid(), file.getOriginalFilename());
                file.transferTo(new File(fileName));
                logger.info(String.format("导入文件:%s", fileName));
                Workbook workbook = new Workbook(fileName);
                Worksheet worksheet = workbook.getWorksheets().get(0);
                List<Map<String, Object>> list = new ArrayList<>();
                Cells cells = worksheet.getCells();
                for (int i = 1; i <= cells.getMaxDataRow(); i++) {
                    Map<String, Object> map = new HashMap<>();
                    for (int j = 0; j <= cells.getMaxDataColumn(); j++) {
                        map.put(cells.get(0, j).getStringValue(), cells.get(i, j).getValue());
                    }
                    list.add(map);
                }
                StringBuilder sb = new StringBuilder();
                for (Map<String, Object> map : list) {
                    try {
                        ReturnInfo result = orderService.impOrder(map, officeCode, currentUser.getId());
                        if (result.resusltCode != 1) {
                            sb.append(String.format("第【" + map.get("序号") + "】 条记录,导入失败:%s<br >", result.getErrorInfo()));
                            failureNum++;
                        } else {
                            successNum++;
                        }
                    } catch (ConstraintViolationException e) {
                        logger.error(e.getMessage());
                        failureNum++;
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        failureNum++;
                    }
                }
                //failureMsg.append(String.format("导入成功：共计【%s】条记录",successNum));
                if (failureNum > 0) {
                    failureMsg.append(String.format("导入失败：共计【%s】条记录<br >", failureNum));
                    failureMsg.append(sb.toString());
                }
                if (successNum > 0) {
                    failureMsg.append(String.format("导入成功：共计【%s】条记录<br >", successNum));
                }
                addMessage(redirectAttributes, failureMsg.toString());
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

        } catch (Exception e) {
            addMessage(redirectAttributes, "订单导入！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/sys/OrderCollection/?repage";
    }

    /***
     * 下载导入模板
     *
     * @Author LH
     * @Description //TODO
     * @Date 6:48 2019/9/17
     * @param request
     * @param response
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @ResponseBody
    //@RequiresPermissions("test:grid:testCountry:import")
    @RequestMapping(value = "import/template")
    public AjaxJson importFileTemplate(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String filePath = this.getClass().getResource("/template/事农国际订货板.xlsx").getPath();
            if (new File(filePath).exists()) {
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                String userAgent = request.getHeader("User-Agent");
                if (/* IE 8 至 IE 10 */
                        userAgent.toUpperCase().contains("MSIE") ||
                                /* IE 11 */
                                userAgent.contains("Trident/7.0")) {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } else if (userAgent.toUpperCase().contains("MOZILLA") ||
                        userAgent.toUpperCase().contains("CHROME")) {
                    fileName = new String(fileName.getBytes(), "ISO-8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                InputStream in = new FileInputStream(filePath);
                int len = 0;
                //5.创建数据缓冲区
                byte[] buffer = new byte[1024];
                //6.通过response对象获取OutputStream流
                OutputStream out = response.getOutputStream();
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                return null;
            } else {
                j.setSuccess(false);
                j.setMsg("导入模板下载失败！文件不存在：");
                return j;
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入模板下载失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    @ResponseBody
    @RequestMapping(value = "user", method = RequestMethod.GET)
    public AjaxJson user(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        User currentUser = UserUtils.getUser();
        ajaxJson.setSuccess(true);
        ajaxJson.setMsg("ab");
//        List<Api> list = new ArrayList<>();
//
//        for (Map<String, Object> map : orderService.ExpBuyerOrderDetail()) {
//            Api a = new Api();
//            a.setTest(Integer.valueOf(map.get("ID").toString()));
//            list.add(a);
//        }
//        Api a1 = new Api();
//        a1.setTest(11);
//        getLicense();
        try {
            Workbook wb = new Workbook("D:\\test.xlsx");
            Worksheet worksheet1 = wb.getWorksheets().get(0);
            worksheet1.getCells().get(0, 0).setValue("供应商：事农国际有限公司");
            WorkbookDesigner designer = new WorkbookDesigner(wb);

            designer.setDataSource("ds", orderService.ExpBuyerOrderDetail());
            designer.process();
            wb.save("D:\\test1.xlsx");
            wb.dispose();
            return downLoadFile(request, response, new File("D:\\test1.xlsx"), "导出订单.xlsx");
            //return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(UserUtils.getOffice(currentUser.getCompany().getId()).getCode());
        return ajaxJson;
    }

    /***
     * 提交导入订单
     *
     * @Author LH
     * @Description //TODO
     * @Date 9:39 2019/9/18
     * @param request
     * @param response
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @ResponseBody
    @RequestMapping(value = "orderCommit", method = RequestMethod.GET)
    public AjaxJson orderCommit(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(false);
        try {
            String ordTime= DictUtils.getDictValue("OrderImpTime","OrderTime","").replace(":","");
            String currTime= DateUtils.getDate("HHmm");
            if(Integer.valueOf(currTime)>=Integer.valueOf(ordTime))
            {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("订货时间己过!");
                return ajaxJson;
            }
            ReturnInfo result = orderService.orderCommit(UserUtils.getUser().getId());
            if (result.getResusltCode() == 1) {
                ajaxJson.setSuccess(true);
                ajaxJson.setMsg(result.getErrorInfo());
            } else {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(result.getErrorInfo());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            ajaxJson.setMsg("订单提交异常!");
        }
        return ajaxJson;
    }

    public AjaxJson downLoadFile(HttpServletRequest request, HttpServletResponse response, File file, String fileName) {
        AjaxJson j = new AjaxJson();
        try {
            String filePath = file.getPath();
            if (new File(filePath).exists()) {
                String userAgent = request.getHeader("User-Agent");
                if (/* IE 8 至 IE 10 */
                        userAgent.toUpperCase().contains("MSIE") ||
                                /* IE 11 */
                                userAgent.contains("Trident/7.0")) {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } else if (userAgent.toUpperCase().contains("MOZILLA") ||
                        userAgent.toUpperCase().contains("CHROME")) {
                    fileName = new String(fileName.getBytes(), "ISO-8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                InputStream in = new FileInputStream(filePath);
                int len = 0;
                //5.创建数据缓冲区
                byte[] buffer = new byte[1024];
                //6.通过response对象获取OutputStream流
                OutputStream out = response.getOutputStream();
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                return null;
            } else {
                j.setSuccess(false);
                j.setMsg("文件下载失败:文件不存在：");
                return j;
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("文件下载失败:失败信息：" + e.getMessage());
        }
        return j;
    }

    @ResponseBody
    @RequestMapping(value = "expBuyerOrderDetail", method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxJson expBuyerOrderDetail(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        User currentUser = UserUtils.getUser();
        ajaxJson.setSuccess(true);
        ajaxJson.setMsg("下载文件失败!");
        try {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            if (!new File(String.format("%s\\UserUpload\\%s\\%s\\", Global.getConfig("userfiles.basedir"), year, month)).exists()) {
                FileUtils.createDirectory(String.format("%s\\UserUpload\\%s\\%s\\", Global.getConfig("userfiles.basedir"), year, month));
            }
            String fileName = String.format("%s\\UserUpload\\%s\\%s\\%s-%s", Global.getConfig("userfiles.basedir"), year, month, IdGen.uuid(), "采购订单.xlsx");
            String filePath = this.getClass().getResource("/template/采购输出模板.xlsx").getPath();
            getLicense();
            Workbook wb = new Workbook(filePath);
            Worksheet worksheet1 = wb.getWorksheets().get(0);
            worksheet1.getCells().get(0, 0).setValue("供应商：事农国际有限公司");
            WorkbookDesigner designer = new WorkbookDesigner(wb);
            designer.setDataSource("ds", orderService.ExpBuyerOrderDetail());
            designer.process();
            wb.save(fileName);
            wb.dispose();
            return downLoadFile(request, response, new File(fileName), "采购订单.xlsx");
            //return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(UserUtils.getOffice(currentUser.getCompany().getId()).getCode());
        return ajaxJson;
    }
    @ResponseBody
    @RequestMapping(value = "expStoreBuyerOrderDetail", method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxJson expStoreBuyerOrderDetail(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        User currentUser = UserUtils.getUser();
        ajaxJson.setSuccess(true);
        ajaxJson.setMsg("下载文件失败!");
        try {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            if (!new File(String.format("%s\\UserUpload\\%s\\%s\\", Global.getConfig("userfiles.basedir"), year, month)).exists()) {
                FileUtils.createDirectory(String.format("%s\\UserUpload\\%s\\%s\\", Global.getConfig("userfiles.basedir"), year, month));
            }
            String fileName = String.format("%s\\UserUpload\\%s\\%s\\%s-%s", Global.getConfig("userfiles.basedir"), year, month, IdGen.uuid(), "物流采购订单.xlsx");
            String filePath = this.getClass().getResource("/template/物流输出模板.xlsx").getPath();
            getLicense();
            Workbook wb = new Workbook(filePath);
            Worksheet worksheet1 = wb.getWorksheets().get(0);
            //worksheet1.getCells().get(0, 0).setValue("供应商：事农国际有限公司");
            WorkbookDesigner designer = new WorkbookDesigner(wb);
            designer.setDataSource("dsStore", orderService.ExpStoreBuyerOrderDetail());
            designer.setDataSource("dsSum", orderService.ExpSumBuyerOrderDetail());
            designer.process();
            wb.save(fileName);
            wb.dispose();
            return downLoadFile(request, response, new File(fileName), "物流采购订单.xlsx");
            //return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(UserUtils.getOffice(currentUser.getCompany().getId()).getCode());
        return ajaxJson;
    }
    @ResponseBody
    @RequiresPermissions("order:collection:list:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(User user,HttpServletResponse response,HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //System.out.println(request.getParameter("ids"));
        if(Global.isDemoMode()){
            j.setSuccess(false);
            j.setMsg("演示模式，不允许操作!");
            return j;
        }
        String ordId=URLDecoder.decode(request.getParameter("ids"));
        ReturnInfo result=orderService.delOrderImp(ordId);
        if(result.getResusltCode()==1){
            j.setSuccess(true);
            j.setMsg("删除成功!");
            return j;
        }
        else {
            j.setSuccess(false);
            j.setMsg(result.getErrorInfo());
            return j;
        }
    }
    @ResponseBody
    @RequiresPermissions("order:collection:time:update")
    @RequestMapping(value = "updateTime")
    public AjaxJson updateTime(HttpServletRequest request,HttpServletResponse response)
    {
        AjaxJson ajaxJson=new AjaxJson();
        try {
            String selectTime=request.getParameter("selectTime");
            if(selectTime==null||selectTime.isEmpty()){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("时间不能为空!");
                return ajaxJson;
            }
            DictValue dictValue= dictTypeService.getDictValue("752f56c87e004816b7729d736ca97ecd");
            dictValue.setValue(selectTime);
            dictTypeService.saveDictValue(dictValue);
            logger.info("订单导入日期修改成功:");
            logger.info(JsonMapper.toJsonString(dictValue));
        }
        catch (Exception e){
            logger.error(e.getMessage());
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("操作异常!");
        }
        return ajaxJson;
    }
    //endregion
}
